<template>
    <div class="app-container">
        <el-form ref="admin" :model="admin" :rules="loginRules" label-width="100px" class="form_admin">
          <el-form-item label="编号">
            <el-input v-model="admin.id" :disabled="true" style="width:320px;" name="id"></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="admin.username" style="width:320px;" @focus="username" name="username"></el-input>
            <el-button @click="updateUsername">修改</el-button>
          </el-form-item>
          <el-form-item label="加密后密码" prop="password">
            <el-input v-model="admin.password" :disabled="true" style="width:320px;" name="password"></el-input>
            <el-button @click="showDialogForm">修改</el-button>
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="admin.nickname" style="width:320px;" name="nickname"></el-input>
            <el-button @click="updateNickname">修改</el-button>
          </el-form-item>

          <el-form-item label="头像上传">

                <!-- 头衔缩略图 -->
                <pan-thumb :image="admin.avatar"/>
                <!-- 文件上传按钮 -->
                <el-button type="primary" icon="el-icon-upload" @click="imagecropperShow=true">更换头像
                </el-button>

                <!--
                    v-show：是否显示上传组件
                    :key：类似于id，如果一个页面多个图片上传控件，可以做区分
                    :url：后台上传的url地址
                    @close：关闭上传组件
                    @crop-upload-success：上传成功后的回调 
                        <input type="file" name="file"/>
                    -->
                <image-cropper
                                v-show="imagecropperShow"
                                :width="200"
                                :height="200"
                                :key="imagecropperKey"
                                :url="BASE_API+'/eduoss/fileoss'"
                                field="file"
                                @close="close"
                                @crop-upload-success="cropSuccess"/>
            </el-form-item>


          <el-form-item label="创建时间">
            <el-date-picker
              v-model="admin.gmtCreate"
              type="datetime"
              :disabled="true"
              placeholder="选择日期时间"
              style="width:320px;"
              name="gmtCreate">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="上次修改时间">
            <el-date-picker
              v-model="admin.gmtModified"
              type="datetime"
              :disabled="true"
              placeholder="选择日期时间"
              style="width:320px;"
              name="gmtModified">
            </el-date-picker>
          </el-form-item>
        </el-form>

        <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="600px" @close="closeUpdatePassword">
          <el-form ref="adminpassword" :model="adminNewPassword" :rules="loginRules">
            <el-form-item label="原密码(加密后)" :label-width="formLabelWidth">
              <el-input v-model="admin.password" :disabled="true" name="password"></el-input>
            </el-form-item>
            <el-form-item label="新密码" :label-width="formLabelWidth" prop="newPassword">
              <el-input v-model="adminNewPassword.newPassword" placeholder='新密码' name="newPassword"></el-input>
            </el-form-item>
            <el-form-item label="重复密码" :label-width="formLabelWidth" prop="repeatPassword">
              <el-input v-model="adminNewPassword.repeatPassword" placeholder="重复密码" name="repeatPassword"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="closeUpdatePassword">取 消</el-button>
            <el-button type="primary" @click="updatePassword">确 定</el-button>
          </div>
        </el-dialog>
    </div>
</template>
<script>
  import profileApi from '@/api/profile/profile'
  import { isvalidUsername } from '@/utils/validate'
  import ImageCropper from '@/components/ImageCropper'
  import PanThumb from '@/components/PanThumb'
  export default {
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!isvalidUsername(value)) {
          callback(new Error('用户名只能为大写、小写英文字母和数字'))
          this.admin.username = this.admin.username_test
        }else if(value.length < 5) {
          callback(new Error('用户名长度不能小于5位'))
          this.admin.username = this.admin.username_test
        }else{
          callback()
        }
      }
      const validatePass = (rule, value, callback) => {
        if(!isvalidUsername(value)){
          callback(new Error('密码只能为大写、小写英文字母和数字'))
        }else if (value.length < 5) {
          callback(new Error('密码不能小于5位'))
        } else {
          callback()
        }
      }
      const validateNewPass = (rule, value, callback) => {
        if(!isvalidUsername(value)){
          callback(new Error('密码只能为大写、小写英文字母和数字'))
          this.adminNewPassword.newPassword = ''
        }else if (value.length < 5) {
          callback(new Error('密码不能小于5位'))
          this.adminNewPassword.newPassword = ''
        } else {
          callback()
        }
      }
      const validateRepeatPass = (rule, value, callback) => {
        if(value !== this.adminNewPassword.newPassword){
          callback(new Error('新密码和就密码不一样'))
          this.adminNewPassword.repeatPassword = ''
        } else {
          callback()
        }
      }
      
      return {
          admin:{
            id: '',
            username: '',
            username_test:'',
            password: '',
            nickname: '',
            avatar: '',
            gmtCreate: '',
            gmtModified: '',
            newPassword: ''//新密码
          },
          adminNewPassword: {
            newPassword: '',//新密码
            repeatPassword: ''//重复密码
          },
          
          loginRules: {
            username: [{ required: true, trigger: 'blur', validator: validateUsername }],
            password: [{ required: true, trigger: 'blur', validator: validatePass }],
            newPassword: [{ required: true, trigger: 'blur', validator: validateNewPass }],
            repeatPassword: [{required: true, trigger: 'blur', validator: validateRepeatPass}]
          },
          formLabelWidth: '120px',
          dialogFormVisible: false,
          imagecropperShow:false,  // 保存按钮是否禁用,
          //上传弹框组件是否显示
          imagecropperKey:0,//上传组件key值
          BASE_API:process.env.BASE_API, //获取dev.env.js里面地址
          saveBtnDisabled:false  // 保存按钮是否禁用,
      }
    },
    components:{
      ImageCropper,
      PanThumb
    },
    created(){
      this.getProfile()
    },
    methods:{
      getProfile(){
        this.$store.dispatch('GetInfo')
          .then(res => {
            this.admin = res.data.admin
          })
      },
      //修改用户名
      updateUsername(){
        profileApi.updateProfile(this.admin)
          .then(res => {
            this.admin = res.data.admin
            this.$message({
              message: '修改用户名成功',
              type: 'success'
            });
          })
      },
      username(){
        this.admin.username_test = this.admin.username;
      },

      //修改真实姓名
      updateNickname(){
        this.$refs.admin.validate(valid => {
          if (valid) {
            this.$store.dispatch('Update', this.admin).then(() => {
              this.getProfile()
              this.$message({
                message: '修改真实姓名成功',
                type: 'success'
              });
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      showDialogForm(){
        this.dialogFormVisible = true
      },
      closeUpdatePassword(){
        this.adminNewPassword.newPassword = ''
        this.adminNewPassword.repeatPassword = ''
        this.dialogFormVisible = false
      },
      //修改密码
      updatePassword(){
        this.$refs.adminpassword.validate(valid => {
          if (valid) {
            this.admin.newPassword = this.adminNewPassword.newPassword
            profileApi.updatePassword(this.admin)
              .then(res => {
                this.admin = res.data.admin
                this.closeUpdatePassword()
                this.$message({
                  message: '修改密码成功',
                  type: 'success'
                });
              })
          } else {
            this.$message.error('请输入正确格式');
            return false
          }
        })
      },
      close() { //关闭上传弹框的方法
          this.imagecropperShow=false
          //上传组件初始化
          this.imagecropperKey = this.imagecropperKey+1
      },
      //上传成功方法
      cropSuccess(data) {
          this.imagecropperShow=false
          //上传之后接口返回图片地址
          this.admin.avatar = data.url
          this.imagecropperKey = this.imagecropperKey+1
          profileApi.updateProfile(this.admin)
            .then(res => {
              this.$message({
                message: '上传头像成功',
                type: 'success'
              });
              this.$store.dispatch('Avatar',this.admin.avatar)
            })
      }
    }
  };
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .svg-container {
    padding: 6px 5px 6px 15px;
    color: $dark_gray;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .form_admin{
    width:500px;
  }
  .form_admin input{
    float:left;
  }
  .form_admin button{
    float: right;
  }
</style>